import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:gbk_codec/gbk_codec.dart';

class StockApiService extends GetxService {
  final Dio _dio = Dio();

  static const String baseUrl = 'https://hq.sinajs.cn';

  @override
  void onInit() {
    super.onInit();
    // 配置Dio拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          // 添加请求头，避免被新浪阻止
          options.headers['Referer'] = 'https://finance.sina.com.cn';
          options.headers['User-Agent'] =
              'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
          return handler.next(options);
        },
      ),
    );
  }

  // 获取股票数据
  Future<String> fetchStockData(String symbol) async {
    try {
      final response = await _dio.get(
        '$baseUrl/list=$symbol',
        options: Options(responseType: ResponseType.bytes),
      );

      if (response.statusCode == 200) {
        // 新浪API返回的数据格式为：var hq_str_sh601006="大秦铁路, 6.890, 6.920, ...";
        String data = gbk_bytes.decode(response.data);


        // 提取数据部分
        RegExp reg = RegExp('="(.*)"');
        Match? match = reg.firstMatch(data);
        print("StockApiService获取数据：$data");

        if (match != null) {
          return match.group(1)!;
        } else {
          throw Exception('数据格式错误');
        }
      } else {
        throw Exception('Failed to load stock data');
      }
    } catch (e) {
      throw Exception('获取股票数据失败: $e');
    }
  }
}
